local function onmax(self, max)
	self.inst.replica.musha_fatiguesleep:SetMax(max)
end

local function oncurrent(self, current)
	self.inst.replica.musha_fatiguesleep:SetCurrent(current)
end

local function OnTaskTick(inst, self, period)
	self:DoDec(period)
end
--ThePlayer.components.musha_fatiguesleep:DoDelta(100)
local Musha_Fatiguesleep =
	Class(
	function(self, inst)
		self.inst = inst
		self.max = 100
		self.current = 0
		local period = 1
		self.inst:DoPeriodicTask(period, OnTaskTick, nil, self, period)
	end,
	nil,
	{
		max = onmax,
		current = oncurrent
	}
)

function Musha_Fatiguesleep:OnSave()
	return {
		max = self.max,
		current = self.current or nil
	}
end

function Musha_Fatiguesleep:OnLoad(data)
	if data ~= nil then
		self.max = data.max
		self.current = data.current
		self:DoDelta(0)
	end
end

function Musha_Fatiguesleep:LongUpdate(dt)
	self:DoDec(dt, true)
end

function Musha_Fatiguesleep:GetDebugString()
	return string.format("%2.2f / %2.2f, rate: (%2.2f)", self.current, self.max, self.inst.musha_settings.Dtired)
end

function Musha_Fatiguesleep:SetMax(amount)
	self.max = amount
	self.current = amount
end

function Musha_Fatiguesleep:DoDelta(delta, overtime, ignore_invincible)
	if self.redirect ~= nil then
		self.redirect(self.inst, delta, overtime)
		return
	end

	if not ignore_invincible and self.inst.components.health.invincible or self.inst.is_teleporting then
		return
	end

	local old = self.current
	self.current = math.clamp(self.current + delta, 0, self.max)

	self.inst:PushEvent(
		"musha_fatiguesleepdelta",
		{oldpercent = old / self.max, newpercent = self.current / self.max, overtime = overtime, delta = self.current - old}
	)
end

function Musha_Fatiguesleep:GetPercent()
	return self.current / self.max
end

function Musha_Fatiguesleep:SetPercent(p, overtime)
	local old = self.current
	self.current = p * self.max
	self.inst:PushEvent("musha_fatiguesleepdelta", {oldpercent = old / self.max, newpercent = p, overtime = overtime})
end

function Musha_Fatiguesleep:DoDec(dt)
	local old = self.current

	local regen = 0
	if self.inst.LightWatcher:IsInLight() then
		if self.inst:HasTag("sleeping") then
			if self.inst.with_fire or self.inst.with_tent then
				regen = -self.inst.musha_settings.Dtired * 1.5
			else
				regen = -self.inst.musha_settings.Dtired
			end
		elseif self.inst.sg:HasStateTag("idle") then
			regen = -0.05 * self.inst.musha_settings.Dtired
		else
			regen = 0.07 * self.inst.musha_settings.Dtired
		end
	else
		regen = 0.15 * self.inst.musha_settings.Dtired
	end
	self:DoDelta((dt * regen), true)
end

return Musha_Fatiguesleep
